/*
 * FileSystemNodeFactory.java
 * 
 * Written by Joseph Bowbeer and released to the public domain,
 * as explained at http://creativecommons.org/licenses/publicdomain
 */

package jozart.dynamictree;

import java.io.File;

import javax.swing.tree.DefaultMutableTreeNode;

/**
 * Implements TreeNodeFactory for a file system. 
 *
 * @author  Joseph Bowbeer
 * @version 1.0.1
 */
public class FileSystemNodeFactory implements TreeNodeFactory {

    /** Absolute path to root file. */
    private final String rootPath;

    /**
     * Create factory rooted at <tt>rootPath</tt>.
     * 
     * @param rootPath absolute path to root directory
     */
    public FileSystemNodeFactory(String rootPath) {
        this.rootPath = rootPath;
    }

    /** {@inheritDoc} */
    public DefaultMutableTreeNode[] createChildren(Object userObject) {
        /* Find parent directory. */
        File parent;
        if (userObject instanceof LinkObject) {
            // file link
            LinkObject link = (LinkObject) userObject;
            parent = (File) link.getObject();
        } else {
            // root link
            parent = new File(rootPath);
        }
        /* Create children. */
        String[] names = parent.isDirectory() ? parent.list() : new String[0];
        int count = names.length;
        DefaultMutableTreeNode[] children =
            new DefaultMutableTreeNode[count];
        for (int i = 0; i < count; i++) {
            File child = new File(parent, names[i]);
            LinkObject link = new LinkObject(names[i], child);
            boolean leaf = child.isFile();
            children[i] = new DefaultMutableTreeNode(link, !leaf);
        }
        return children;
    }
}
